package com.ict.http;

import com.ict.interceptor.CustomHttpLoggingInterceptor;
import com.ict.interceptor.RetryInterceptor;
import com.ict.interceptor.SignatureInterceptor;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.security.PrivateKey;
import java.util.Collections;

/**
 * @author wujinpeng
 * @version 1.0
 * @date 2024/8/31 20:43
 * @description
 */
@Configuration
public class RestTemplateConf {

    @Autowired
    private PrivateKey privateKey;

    @Bean
    public RestTemplate restTemplate() {

        // 创建连接池管理器
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(100); // 最大连接数
        connectionManager.setDefaultMaxPerRoute(20); // 每个路由的最大连接数

        // 配置请求超时 设置代理
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000) // 连接超时
                .setSocketTimeout(5000)  // 读取超时
                .build();

        // 配置代理的认证,如果连接代理主机有用户名和密码
//        CredentialsProvider credsProvider = new BasicCredentialsProvider();
//        credsProvider.setCredentials(
//                new AuthScope("proxy.example.com", 8080),
//                new UsernamePasswordCredentials("username", "password")
//        );

        // 创建 HttpClient 实例，设置代理和认证
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
//                .setProxy(new HttpHost("127.0.0.1", 7890))
//                .setDefaultCredentialsProvider(credsProvider) //代理认证
                .build();

        // 创建 HttpComponentsClientHttpRequestFactory
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

        // 配置 RestTemplate
        RestTemplate restTemplate = new RestTemplate(factory);

        // 配置重试机制
        // 最多重试 3 次
        restTemplate.setInterceptors(Collections.singletonList(new RetryInterceptor(3)));

        // Optional: 配置自定义拦截器来处理请求和响应日志
        restTemplate.getInterceptors().add(new CustomHttpLoggingInterceptor());

        restTemplate.getInterceptors().add(new SignatureInterceptor(privateKey));
        // 配置自定义异常处理来处理异常情况
        restTemplate.setErrorHandler(new MyRestErrorHandler());

        return restTemplate;
    }
}
